<template>
  <div class="credit_detail_page">
    <div class="check_mod fail_mod" v-if="detailObj.status === '40'">
      <img src="@/assets/icons/fail_status.png" alt="" class="icon">
      <div class="reason_box">
        <span class="reason">驳回原因：</span>
        <span class="text">{{ detailObj.remark }}</span>
      </div>
    </div>
    <div class="check_mod success_mod" v-else-if="detailObj.status === '30'">
      <i class="el-icon-success icon"></i>
      <div class="reason_box">
        <span class="reason">授信成功</span>
      </div>
    </div>
    <div class="mod">
      <div class="title">
        <i class="icon"></i>
        基本信息
      </div>
      <div class="content">
        <el-row class="row">
          <el-col :span="8">
            <div class="cell">
              <div class="key">授信类型：</div>
              <div class="value">{{ detailObj.creditTypeName }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="cell">
              <div class="key">资金机构：</div>
              <div class="value">{{ detailObj.jigouName }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="cell">
              <div class="key">核心企业：</div>
              <div class="value">{{ detailObj.hexinName }}</div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <div class="mod">
      <div class="title">
        <i class="icon"></i>
        财务数据
      </div>
      <div class="content">
        <el-row class="row">
          <el-col :span="8">
            <div class="cell">
              <div class="key">企业总资产金额（元）：</div>
              <div class="value">{{ detailObj.totalAssets }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="cell">
              <div class="key">上半年销售金额（元）：</div>
              <div class="value">{{ detailObj.halfAssets }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="cell">
              <div class="key">上一年纳税总金额（元）：</div>
              <div class="value">{{ detailObj.taxesAssets }}</div>
            </div>
          </el-col>
        </el-row>
        <el-row class="row">
          <el-col :span="8">
            <div class="cell">
              <div class="key">上一年应收总金额（元）：</div>
              <div class="value">{{ detailObj.receivableAssets }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="cell">
              <div class="key">上一年流水总金额（元）：</div>
              <div class="value">{{ detailObj.waterAssets }}</div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <div class="mod">
      <div class="title">
        <i class="icon"></i>
        项目信息
      </div>
      <div class="content">
        <el-row class="row">
          <el-col :span="8">
            <div class="cell">
              <div class="key">项目名称：</div>
              <div class="value">{{ detailObj.projectInfo.pName }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="cell">
              <div class="key">项目类型：</div>
              <div class="value">{{ detailObj.projectInfo.pType }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="cell">
              <div class="key">项目总金额（元）：</div>
              <div class="value">{{ detailObj.projectInfo.pAmount }}</div>
            </div>
          </el-col>
        </el-row>
        <el-row class="row">
          <el-col :span="8">
            <div class="cell">
              <div class="key">预付款日期：</div>
              <div class="value">{{ detailObj.projectInfo.advancesReceivedDate }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="cell">
              <div class="key">预付款金额（元）：</div>
              <div class="value">{{ detailObj.projectInfo.advancesReceivedAmount }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="cell">
              <div class="key">项目预交付日期：</div>
              <div class="value">{{ detailObj.projectInfo.pDeliverDate }}</div>
            </div>
          </el-col>
        </el-row>
        <el-row class="row">
          <el-col :span="8">
            <div class="cell">
              <div class="key">是否已签合同：</div>
              <!-- {{ detailObj.projectInfo.pStatus }} -->
                <!-- test -->
              <div class="value"></div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <div class="mod">
      <div class="title">
        <i class="icon"></i>
        贸易合同
      </div>
      <el-table :data="detailObj.tradeContractInfo" border>
        <el-table-column
          label="序号"
          type="index"
        >
        </el-table-column>
        <el-table-column
          v-for="(item, index) in contractColumns"
          :key="item.label"
          v-bind="item"
        >
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text">
              <a :href="baseURL + scope.row.url" target="_blank">预览</a>
            </el-button>
            <el-button type="text" @click="delContractRow(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="mod">
      <div class="title">
        <i class="icon"></i>
        贸易发票
      </div>
      <el-table :data="detailObj.tradeInvoiceInfo" border>
        <el-table-column
          v-for="item in invoiceColumns"
          :key="item.label"
          v-bind="item"
        >
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="previewBigImg(scope.row.url)">预览</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="total_box">
        共计发票金额：<span class="total">{{ detailObj.invoiceTotalAmount }}</span>
      </div>
    </div>
    <div class="mod">
      <div class="title">
        <i class="icon"></i>
        锁定银行账号
      </div>
      <div class="content">
        <el-row class="row">
          <el-col :span="8">
            <div class="cell">
              <div class="key">开户银行：</div>
              <div class="value">{{ enterpriseBankObj.accountName }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="cell">
              <div class="key">银行账号：</div>
              <div class="value">{{ enterpriseBankObj.bankNumber }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="cell">
              <div class="key">开户支行：</div>
              <div class="value">{{ enterpriseBankObj.bankBranch }}</div>
            </div>
          </el-col>
        </el-row>
        <el-row class="row">
          <el-col :span="8">
            <div class="cell">
              <div class="key">大额行号：</div>
              <div class="value">{{ enterpriseBankObj.bankCode }}</div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <div class="mod" v-if="detailObj.otherInfo && detailObj.otherInfo.length">
      <div class="title">
        <i class="icon"></i>
        其他资料
      </div>
      <el-table :data="detailObj.otherInfo" border>
        <el-table-column label="序号" type="index" width="200px"></el-table-column>
        <el-table-column
          v-for="item in otherColumns"
          :key="item.label"
          :label="item.label"
          :prop="item.prop"
        >
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text">
              <a :href="baseURL + scope.row.url" target="_blank">查看</a>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-if="detailObj.auditInfo">
      <div class="mod">
        <div class="title">
          <i class="icon"></i>
          申请审核
        </div>
        <div class="check_content">
          <div class="check_line">
            <div class="key">审核状态</div>
            <div class="value">
              <el-button
                class="btn left_btn"
                :type="status === 30 ? 'primary' : ''"
                @click="status = 30"
              >审核通过</el-button>
              <el-button
                class="btn right_btn"
                :type="status === 40 ? 'danger' : ''"
                @click="status = 40"
              >驳回修改</el-button>
            </div>
          </div>
          <div class="check_line">
            <div class="key key_reason">审核原因</div>
            <div class="value">
              <el-form
                ref="checkForm"
                :model="checkForm"
                :rules="status === 40 ? checkRules : {}"
              >
                <el-form-item prop="remark" >
                  <el-input
                    type="textarea"
                    placeholder="请输入审核建议内容"
                    :rows="5"
                    class="textarea"
                    v-model="checkForm.remark"
                  ></el-input>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </div>
      </div>
      <div class="mod">
        <div class="title">
          <i class="icon"></i>
          签署协议
        </div>
        <div class="content">
          <div class="btns">
            <el-button
              class="btn"
              plain
            >取 消</el-button>
            <el-button
              class="btn btn_right"
              :type="status === 30 ? 'primary' : status === 40 ? 'danger' : ''"
              :disabled="status !== 30 && status !== 40"
              :loading="checkLoading"
              @click="check"
            >
              {{ status === 40 ? '驳回申请' : '签署协议'}}
            </el-button>
          </div>
        </div>
      </div>
    </div>
    <CustomDialog
      title="查看内容"
      width="70%"
      :visible="dialogVisible"
      @close="dialogVisible = false"
    >
      <div class="mask_dialog_content">
        <div class="img_box">
          <img :src="baseURL+ previewBigImgUrl" alt="" class="img" />
        </div>
      </div>
    </CustomDialog>
  </div>
</template>

<script>
import { creditDetail, creditCheck } from '@/api/production'
import { bankList } from '@/api/companyManage'
import CustomDialog from '@/customComponents/dialog'

export default {
  components: {
    CustomDialog,
  },
  data() {
    return {
      baseURL: process.env.NODE_ENV === 'development' ? process.env.VUE_APP_BASE_API :
        process.env.VUE_APP_HTTP_REQUEST_ADDRESS,
      id: '',
      detailObj: {
        creditType: '', // 授信类型
        creditTypeName: '', // 授信类型名
        jigouName: '', // 资金机构
        hexinName: '', // 核心企业
        totalAssets: '', // 企业总资产金额（元）
        halfAssets: '', // 上半年销售金额（元）
        taxesAssets: '', // 上一年纳税总金额（元）
        receivableAssets: '', // 上一年应收总金额（元）
        waterAssets: '', // 上一年流水总金额（元）

        projectInfo: { // 项目信息
          pName: '', // 项目名称
          pType: '', // 项目类型
          pAmount: '', // 项目总金额（元）
          advancesReceivedDate: '', // 预收款日期
          advancesReceivedAmount: '', // 预收款金额（元）
          pStatus: '', // 项目状态
          pDeliverDate: '', // 项目预交付日期
        },
        tradeContractInfo: [], // 贸易合同数据
        tradeInvoiceInfo: [], // 贸易发票数据
        invoiceTotalAmount: 0, // 发票总金额
        enterpriseBankId: '', // 银行账户id

      },
      contractColumns: [], // 贸易合同列
      invoiceColumns: [], // 贸易发票列
      otherColumns: [], // 其他资料列
      dialogVisible: false, // 预览图弹窗
      previewBigImgUrl: '', // 预览图
      bankAccountList: [], // 银行账户列表
      enterpriseBankObj: {
        accountName: '',
        bankNumber: '',
        bankBranch: '',
        bankCode: '',
      }, // 银行信息
      userType: '', // 用于判断是授信详情，还是锁定账户详情
      status: '', // 提交审核用，传30成功，传40失败
      checkForm: {
        remark: '', // 审核原因
      },
      checkRules: {
        remark: [
          { required: true, trigger: ['change', 'blur'], message: '请输入审核建议内容' },
        ]
      },
      checkLoading: false,
    }
  },
  created() {
    this.contractColumns = [
      {
        label: '合同名称',
        prop: 'contractName'
      },
      {
        label: '合同编号',
        prop: 'contractCode'
      },
      {
        label: '合同金额',
        prop: 'contractAmount'
      },
      {
        label: '合同签订日期',
        prop: 'contractDateStart',
        type: 'date',
      },
      {
        label: '合同结束日期',
        prop: 'contractDateEnd',
        type: 'date',
      },
    ]
    this.invoiceColumns = [
      {
        label: '序号',
        type: 'index',
      },
      {
        label: '发票类型',
        prop: 'invoiceTypeDesc'
      },
      {
        label: '发票代码',
        prop: 'code'
      },
      {
        label: '发票号码',
        prop: 'no'
      },
      {
        label: '发票金额(元)',
        prop: 'sumAmount'
      },
      {
        label: '开票日期',
        prop: 'date'
      },
      {
        label: '购买方',
        prop: 'buyerName'
      },
      {
        label: '销售方',
        prop: 'sellerName'
      },
    ]
    this.otherColumns = [
      {
        label: '文件名称',
        prop: 'fileName'
      },
    ]
  },
  watch: {
    status: {
      handler: function (newVal, oldVal) {
        if (newVal !== 40) {
          this.$refs.checkForm.clearValidate()
        }
      }
    },
    '$route.path': {
      handler: function (newVal) {
        if (newVal.indexOf('lockCreditDetail') > -1) {
          this.userType = 50
        } else {
          this.userType = 10
        }
        console.log(this.userType)
      },
      immediate: true,
      deep: true,
    }
  },
  mounted() {
    Promise.all([
      this.getCreditType(),
      this.getBankAccountList()
    ]).then(() => {
      if (this.$route.query.id) {
        this.id = this.$route.query.id
        this.getCreditDetail(this.id)
      }
    })
  },
  methods: {
    // 获取授信类型
    getCreditType() {
      return new Promise((resolve, reject) => {
        this.getDicts('credit').then((res) => {
          if (res.code === 200) {
            this.creditTypeList = res.data
            resolve()
          } else {
            reject()
          }
        })
      })
    },
    // 获取用户银行账户列表
    getBankAccountList() {
      return new Promise((resolve, reject) => {
        bankList().then((res) => {
          if (res.code === 200) {
            this.bankAccountList = res.rows
            resolve()
          } else {
            reject()
          }
        })
      })
    },
    getCreditDetail() {
      // const data = JSON.parse('{"creditType":"20","jigouName":"厦门银行","hexinName":"核心企业有限公司","totalAssets":"1000","halfAssets":"550","taxesAssets":"100","receivableAssets":"100","waterAssets":"2000","projectInfo":"{\\"pName\\":\\"大项目1\\",\\"pType\\":\\"物资采购类\\",\\"pAmount\\":\\"900\\",\\"advancesReceivedDate\\":\\"2025-03-02\\",\\"advancesReceivedAmount\\":\\"100\\",\\"pStatus\\":\\"10\\",\\"pDeliverDate\\":\\"2025-04-04\\"}","tradeInvoiceInfo":"[{\\"type\\":\\"20101\\",\\"invoiceTypeDesc\\":\\"山东增值税专用发票\\",\\"code\\":\\"3700174130\\",\\"no\\":\\"07758015\\",\\"checkAmount\\":70137.06,\\"date\\":\\"20181004\\",\\"sumAmount\\":81359,\\"pretaxAmount\\":70137.06,\\"buyerName\\":\\"香河万利通实业有限公司\\",\\"buyerBank\\":\\"工行廊坊和平支行0410002619300048085\\",\\"sellerName\\":\\"招远市江龙石材有限公司\\",\\"sellerBank\\":\\"招远市农村信用合作联社宋家信用社90606491020100023394\\",\\"check\\":true,\\"vcode\\":\\"\\",\\"typeDesc\\":\\"增值税专用发票\\",\\"url\\":\\"/profile/upload/2025/02/27/发票1_20250227131739A022.jpg\\"}]","invoiceTotalAmount":81359,"enterpriseBankId":11,"otherInfo":"[]","tradeContractInfo":"[{\\"contractName\\":\\"大合同\\",\\"contractCode\\":\\"0000\\",\\"contractAmount\\":\\"5000\\",\\"contractDateStart\\":\\"2025-03-04\\",\\"contractDateEnd\\":\\"2025-03-05\\",\\"url\\":\\"/profile/upload/2025/02/27/贸易合同_20250227131415A021.pdf\\"}]"}')
      // console.log(JSON.parse(data.projectInfo))
      creditDetail(this.id, this.userType).then((res) => {
        this.detailObj = res.data
        // Object.keys(this.detailObj).forEach((key) => {
        //   this.detailObj[key] = data[key]
        // })
        this.detailObj.creditTypeName = this.creditTypeList.find((item) => {
          if (item.dictValue === this.detailObj.creditType) {
            return item
          }
        })?.dictLabel || ''
        this.detailObj.projectInfo = JSON.parse(res.data.projectInfo || '{}')
        this.detailObj.tradeContractInfo = JSON.parse(res.data.tradeContractInfo || '[]')
        this.detailObj.tradeInvoiceInfo = JSON.parse(res.data.tradeInvoiceInfo || '[]')
        this.accountNameChange(this.detailObj.enterpriseBankId)
        this.detailObj.otherInfo = JSON.parse(res.data.otherInfo || '[]')
        console.log(this.detailObj)
      })
    },
    // 开户银行change
    accountNameChange(value) {
      const item = this.bankAccountList.find((item) => {
        if (item.bankDeposit === value + '') {
          return item
        }
      })
      if (item) {
        this.enterpriseBankObj = { ...this.enterpriseBankObj, ...item }
      }
    },
    // 预览发票大图
    previewBigImg(url) {
      this.previewBigImgUrl = url
      this.dialogVisible = true
    },
    // 融资审核
    check() {
      // status=30&remark=&userType=10
      if (this.status === 40) {
        this.$refs.checkForm.validate((valid) => {
          if (valid) {
            this.creditCheck()
          }
        })
      } else {
        this.creditCheck()
      }
    },
    creditCheck() {
      this.checkLoading = true
      creditCheck(
        this.id,
        {
          status: this.status,
          remark: this.checkForm.remark,
          userType: this.userType,
        }
      ).then((res) => {
        this.checkLoading = false
        this.$message({
          type: 'success',
          message: this.status === 30 ? '审核成功' : '驳回成功',
          onClose: () => {
            this.$router.back()
          }
        })
      }).catch(() => {
        this.checkLoading = false
        this.$router.back()
      })
    },
  }
}
</script>

<style lang="scss" scoped>
@import '@/assets/styles/variables.scss';

.credit_detail_page {
  .check_mod {
    border-radius: 12px;
    padding: 26px 30px;
    margin-bottom: 16px;
    display: flex;
    align-items: center;
  }
  .fail_mod {
    border: 1px solid #FF4D4F;
    background-color: #FFF7F6;
    .icon {
      display: block;
      width: 48px;
      height: 48px;
      margin-right: 10px;
    }
    .reason_box {
      color: #FF4D4F;
      font-weight: 600;
      .reason {
        font-size: 20px;
        margin-right: 8px;
      }
      .text {
        font-size: 14px;
      }
    }
  }
  .success_mod {
    border: 1px solid rgb(194, 231, 176);
    background-color: rgb(240, 249, 235);
    .icon {
      font-size: 48px;
      margin-right: 10px;
      color: rgb(103, 194, 58);
    }
    .reason_box {
      color: rgb(103, 194, 58);
      font-weight: 600;
      .reason {
        font-size: 20px;
        margin-right: 8px;
      }
    }
  }
  .mod {
    background-color: #fff;
    box-shadow: 0 1px 2px 0 rgba(1, 24, 70, 0.09);
    border-radius: 6px;
    margin-bottom: 16px;
    padding: 20px 16px 24px;
    .title {
      color: #333;
      font-size: 16px;
      font-weight: 600;
      display: flex;
      align-items: center;
      margin-bottom: 20px;
      .icon {
        width: 3px;
        height: 16px;
        border-radius: 1px;
        background-color: $theme;
        margin-right: 5px;
      }
    }
    .content {
      .row {
        margin-bottom: 38px;
        .cell {
          display: flex;
          align-items: center;
          .key {
            color: #777;
            font-size: 14px;
            width: 195px;
            text-align: right;
          }
          .value {
            color: #333;
            font-size: 14px;
          }
        }
      }
      .btns {
        display: flex;
        justify-content: center;
        align-items: center;
        .btn {
          width: 140px;
        }
        .btn_right {
          margin-left: 24px;
        }
      }
    }
    .check_content {
      padding: 40px 300px 40px 146px;
      .check_line {
        display: flex;
        align-items: center;
        margin-bottom: 20px;
        &:last-child {
          margin-bottom: 0;
        }
        .key {
          color: #777;
          font-size: 14px;
          margin-right: 10px;
          &.key_reason {
            align-self: flex-start;
            margin-top: 20px;
          }
        }
        .value {
          flex: 1 1 auto;
          .btn {
            width: 120px;
          }
          .right_btn {
            margin-left: 20px;
          }
          .textarea {
            width: 100%;
          }
        }
      }
    }
    .total_box {
      height: 32px;
      line-height: 32px;
      background-color: #FFFAF4;
      color: #333;
      font-size: 14px;
      font-weight: 500;
      border-radius: 2px;
      padding-left: 28px;
      margin-top: 20px;
      .total {
        color: #FF4D4F;
        font-size: 20px;
      }
    }
  }
}
</style>
